package cn.tedu.dada.user.service.impl;

import cn.tedu.dada.base.exception.ServiceException;
import cn.tedu.dada.base.response.StatusCode;
import cn.tedu.dada.user.mapper.UserMapper;
import cn.tedu.dada.user.pojo.dto.UserLoginParam;
import cn.tedu.dada.user.pojo.vo.UserVO;
import cn.tedu.dada.user.pojo.dto.UserRegParam;
import cn.tedu.dada.user.pojo.entity.User;
import cn.tedu.dada.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录:userLoginParam={}", userLoginParam);
        System.out.println(userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        log.debug("1111{}",userVO);
        System.out.println(userVO);
        if (userVO == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

    @Override
    public void userReg(UserRegParam userRegParam) {
        log.debug("用户注册:userRegParam={}", userRegParam);
        UserVO userVO = userMapper.selectByUsername(userRegParam.getUsername());
        if (userVO == null) {
            User user = new User();
            BeanUtils.copyProperties(userRegParam, user);
            user.setRegDate(new Date());
            userMapper.userReg(user);
        } else {
            System.out.println(111111);
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }
    }
}